import adodbapi
import jedi.utils

import torch
from torch import nn
from d2l import torch as d2l

# NiN网络
# def nin_block(in_channels,out_channels,kernel_size,strides,padding):
#     return nn.Sequential(
#         nn.Conv2d(in_channels,out_channels,kernel_size,strides,padding),nn.ReLU(),
#         nn.Conv2d(out_channels,out_channels,kernel_size=1),nn.ReLU(),
#         nn.Conv2d(out_channels,out_channels,kernel_size=1),nn.ReLU())
#
# net = nn.Sequential(
#     nin_block(1,96,kernel_size=11,strides=4,padding=0),
#     nn.MaxPool2d(3, stride=2),
#     nin_block(96,256,kernel_size=5,strides=1,padding=2),
#     nn.MaxPool2d(kernel_size=3,stride=2),
#     nin_block(256,384,kernel_size=3,strides=1,padding=1),
#     nn.MaxPool2d(kernel_size=3,stride=2),nn.Dropout(0.5),
#     nin_block(384,10,kernel_size=3,strides=1,padding=1),
#     nn.AdaptiveAvgPool2d((1,1)),
#     nn.Flatten())
#
# # X = torch.rand(size=(1,1,224,224))
# # for layer in net:
# #     X = layer(X)
# #     print(f"{layer.__class__.__name__}:output shape:{X.shape}")
#
# lr,num_epochs,batch_size = 0.05,10,128
# train_iter,test_iter = d2l.load_data_fashion_mnist(batch_size=batch_size,resize=224)
# d2l.train_ch6(net,train_iter,test_iter,num_epochs,lr,device=d2l.try_gpu())
# d2l.plt.show()

# from torch.nn import functional as F
# # GoogleNet
# class Inception(nn.Module):
#     # c1--c4是每条路径的输出通道数
#     def __init__(self, in_channels, c1, c2, c3, c4, **kwargs):
#         super(Inception, self).__init__(**kwargs)
#         # 线路1，单1x1卷积层
#         self.p1_1 = nn.Conv2d(in_channels, c1, kernel_size=1)
#         # 线路2，1x1卷积层后接3x3卷积层
#         self.p2_1 = nn.Conv2d(in_channels, c2[0], kernel_size=1)
#         self.p2_2 = nn.Conv2d(c2[0], c2[1], kernel_size=3, padding=1)
#         # 线路3，1x1卷积层后接5x5卷积层
#         self.p3_1 = nn.Conv2d(in_channels, c3[0], kernel_size=1)
#         self.p3_2 = nn.Conv2d(c3[0], c3[1], kernel_size=5, padding=2)
#         # 线路4，3x3最大汇聚层后接1x1卷积层
#         self.p4_1 = nn.MaxPool2d(kernel_size=3, stride=1, padding=1)
#         self.p4_2 = nn.Conv2d(in_channels, c4, kernel_size=1)
#
#     def forward(self, x):
#         p1 = F.relu(self.p1_1(x))
#         p2 = F.relu(self.p2_2(F.relu(self.p2_1(x))))
#         p3 = F.relu(self.p3_2(F.relu(self.p3_1(x))))
#         p4 = F.relu(self.p4_2(self.p4_1(x)))
#         # 在通道维度上连结输出
#         return torch.cat((p1, p2, p3, p4), dim=1)
#
# b1 = nn.Sequential(nn.Conv2d(1, 64, kernel_size=7, stride=2, padding=3),
#                    nn.ReLU(),
#                    nn.MaxPool2d(kernel_size=3, stride=2, padding=1))
#
# b2 = nn.Sequential(nn.Conv2d(64, 64, kernel_size=1),
#                    nn.ReLU(),
#                    nn.Conv2d(64, 192, kernel_size=3, padding=1),
#                    nn.ReLU(),
#                    nn.MaxPool2d(kernel_size=3, stride=2, padding=1))
#
# b3 = nn.Sequential(Inception(192, 64, (96, 128), (16, 32), 32),
#                    Inception(256, 128, (128, 192), (32, 96), 64),
#                    nn.MaxPool2d(kernel_size=3, stride=2, padding=1))
#
# b4 = nn.Sequential(Inception(480, 192, (96, 208), (16, 48), 64),
#                    Inception(512, 160, (112, 224), (24, 64), 64),
#                    Inception(512, 128, (128, 256), (24, 64), 64),
#                    Inception(512, 112, (144, 288), (32, 64), 64),
#                    Inception(528, 256, (160, 320), (32, 128), 128),
#                    nn.MaxPool2d(kernel_size=3, stride=2, padding=1))
#
# b5 = nn.Sequential(Inception(832, 256, (160, 320), (32, 128), 128),
#                    Inception(832, 384, (192, 384), (48, 128), 128),
#                    nn.AdaptiveAvgPool2d((1,1)),
#                    nn.Flatten())
#
# net = nn.Sequential(b1, b2, b3, b4, b5, nn.Linear(1024, 10))
#
# # X = torch.rand(size=(1, 1, 96, 96))
# # for layer in net:
# #     X = layer(X)
# #     print(layer.__class__.__name__,'output shape:\t', X.shape)
#
# lr, num_epochs, batch_size = 0.05, 10, 128
# train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size, resize=96)
# d2l.train_ch6(net, train_iter, test_iter, num_epochs, lr, d2l.try_gpu())
# d2l.plt.show()

# 批量归一化

def batch_norm(X,gamma,beta,moving_mean,moving_var,eps,momentum):
    if not torch.is_grad_enabled():  # 如果表示训练模式，使用全局的mean和var
        X_hat = (X-moving_mean)/torch.sqrt(moving_var+eps)
    else:
        assert  len(X.shape) in (2,4)
        if len(X.shape)==2:
            mean = X.mean(dim=0)
            var = ((X-mean)**2).mean(dim=0)
        else:
            mean = X.mean(dim=(0,2,3),keepdim=True)
            var = ((X-mean)**2).mean(dim=(0,2,3),keepdim=True)
        X_hat = (X-mean)/torch.sqrt(var+eps)
        moving_mean = momentum*moving_mean +(1.0-momentum)*mean
        moving_var = momentum*moving_var +(1.0-momentum)*var
    Y = gamma*X_hat+beta
    return Y,moving_mean.data,moving_var.data

class BatchNorm(nn.Module):
    def __init__(self,num_features,num_dims):
        super().__init__()
        if(num_dims==2):
            shape = (1,num_features)
        else:
            shape = (1,num_features,1,1)
        self.gamma = nn.Parameter(torch.ones(shape))
        self.beta = nn.Parameter(torch.zeros(shape))
        self.moving_mean = torch.zeros(shape)
        self.moving_var = torch.ones(shape)

    def forward(self,X):
        if self.moving_mean.device != X.device:
            self.moving_mean=self.moving_mean.to(X.device)
            self.moving_var = self.moving_var.to(X.device)
        Y,self.moving_mean,self.moving_var =batch_norm(X,self.gamma,self.beta,
                self.moving_mean,self.moving_var,eps=1e-5,momentum=0.9)
        return Y

net = torch.nn.Sequential(
    Reshape(),nn.Conv2d(1,6,kernel_size=5),BatchNorm(6,num_dims=4),
    nn.ReLU(),nn.MaxPool2d(kernel_size=2,stride=2),
    nn.Conv2d(6,16,kernel_size=5),BatchNorm(16,num_dims=4),nn.ReLU(),
    nn.MaxPool2d(kernel_size=2,stride=2),nn.Flatten(),
    nn.Linear(16*4*4,120),BatchNorm(120,num_dims=2),nn.ReLU(),
    nn.Linear(120,84),nn.ReLU(),
    nn.Linear(84,10))

lr, num_epochs, batch_size = 1.0, 10, 256
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)
d2l.train_ch6(net, train_iter, test_iter, num_epochs, lr, d2l.try_gpu())
d2l.plt.show()